package com.boot.down.service.impl;

import com.boot.down.entity.GradeData;
import com.boot.down.service.ICounter;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

/**
 * @author dell
 */
@Service
public class CounterImpl implements ICounter {

	private static Integer count;
	/**
	 * 1秒
	 */
	private static final long ONE_SECOND = 1000;
	/**
	 * 60秒
	 */
	private static final long ONE_MINUTE = 60;

	private static long startTime = System.currentTimeMillis();

	static List<Integer> list;
	static {
		count = 0;
		list = new LinkedList<Integer>();
	}

	@Override
	@Async
	public void hit() {
		long endTime = System.currentTimeMillis();
		count = count + 1;
		if ((endTime - startTime) == ONE_SECOND) {
			startTime = endTime;
			//如果数据过多怎么处理栈溢出
			list.add(count);
			count = 0;
		}
	}

	@Override
	@Async
	public GradeData gaveData() {

		GradeData gradeData = new GradeData();
		List<Integer> last60second = new LinkedList<>();
		if(list.size() > ONE_MINUTE){
			for (int i = list.size()-1; i >= 0; i--){
				if(i >= (list.size() -61)){
					last60second.add(list.get(i));
				}
			}
		}else{
			last60second.addAll(list);
		}
		gradeData.setTime60second(last60second);
        //10s平均数
		gradeData.setTime10second(getAverageBySecond(10));
		//10分钟平均数
		gradeData.setTime10minute(getAverageBySecond(10 * 60));
		//60分钟平均数
		gradeData.setTime60minute(getAverageBySecond(60 * 60));
		return gradeData;
	}

	/**
	 * 得到平均数,根据输入的时间
	 * @param second
	 * @return
	 */
	private int getAverageBySecond(int second){

		int averageNum = 0;
		if(list.size() > second){
			for(int i = list.size()-1; i >= 0; i--){
				if(i >= (list.size()) - (second+1)){
					averageNum += list.get(i);
				}
			}
			//计算平均数
			averageNum = averageNum/second;
		}else{
		    for(int num : list){
		    	averageNum += num;
			}
			//计算平均数
			averageNum = averageNum/list.size();
		}
		return averageNum;
	}
}
